package javaer.starter.web.controller;

import javaer.starter.base.domain.dto.NewProjectDefinition;
import javaer.starter.base.domain.vo.ResultVO;
import javaer.starter.constant.StorePathEnum;
import javaer.starter.core.Bootstrap;
import javaer.starter.core.BuildContext;
import javaer.starter.util.Base64Util;
import javaer.starter.util.FileUtil;
import javaer.starter.util.ZIPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author yangzhen
 * @date 2023/6/7 17:36
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping
public class StarterController {

    @Resource
    private Bootstrap bootstrap;

    @PostMapping("/init")
    public Object init(@RequestBody NewProjectDefinition projectDefinition, HttpServletRequest request) {

        try {
            Path path = null;
            BuildContext buildContext = bootstrap.generate(projectDefinition);
            path = buildContext.getProjectPath();
            String filename = projectDefinition.getArtifactId() + System.currentTimeMillis() + ".zip";
            filename = ZIPUtil.decompress(path.toFile(), filename);
            log.info(filename);
            filename = StorePathEnum.ARCHIVE_PATH.getPath().relativize(Paths.get(filename)).toString();
            filename = Base64Util.encode(filename.replace("../", ""));
            return ResultVO.success(filename);
        } catch (Exception exception) {
            log.error(exception.getMessage(), exception);
            if (exception instanceof InterruptedException) {
                return ResultVO.error("项目生成时中断");
            }
            return ResultVO.error("项目生成失败");
        } finally {
        }
    }


    @GetMapping(path = "/download.zip")
    public Object download(HttpServletRequest httpServletRequest,
                           String path,
                           String name) throws Exception {

        path = Base64Util.decode(path);

        Path storePath = StorePathEnum.ARCHIVE_PATH.getPath().resolve(path);

        org.springframework.core.io.Resource resource = new UrlResource(storePath.toUri());
        if (!resource.exists()) {
            return ResultVO.error("程序包不存在", ResultVO.ResultConsts.FAILURE_CODE);
        }
        String contentType = httpServletRequest.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        log.info("获取应用压缩文件成功，开始删除原始目录");
        // 删除原文件
        Path projectPath = StorePathEnum.PROJECT_PATH.getPath().resolve(name);
        if (Files.exists(projectPath)) {
            FileUtil.deleteProject(projectPath);
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + ".zip\"")
                .body(resource);
    }

}
